/*
 * Copyright 2009 Cedric Priscal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package com.zhxh.nzpos.serialport;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidParameterException;

import szxb.test.ll.jni.test4052;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android_serialport_api.SerialPort;

import com.zhxh.nzpos.Constants;
import com.zhxh.nzpos.R;

/**
 * 读取卡信息父类
 * 
 * @author wangzt
 * 
 */
public abstract class ReadSerialPort extends Activity {

	// 修改密码
	byte[] mValueToWrite31 = { (byte) 0x9b, (byte) 0x0f, (byte) 0x00,
			(byte) 0x13, (byte) 0x33, (byte) 0x03, (byte) 0x01, (byte) 0x31,
			(byte) 0x32, (byte) 0x33, (byte) 0x34, (byte) 0x35, (byte) 0x36,
			(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
			(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
			(byte) 0xb1 };

	// byte mValueToSend;

	byte[] mValueRead10 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x01, (byte) 0x00, (byte) 0xa5 };

	// 读取身份证信息
	byte[] mValueRead20 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x02, (byte) 0x00, (byte) 0xa6 };
	byte[] mValueRead21 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x02, (byte) 0x01, (byte) 0xa7 };
	byte[] mValueRead22 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x02, (byte) 0x02, (byte) 0xa4 };
	byte[] mValueRead23 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x02, (byte) 0x03, (byte) 0xa5 };
	// 身份证号
	protected String idcard1 = "";
	protected String idcard2 = "";
	
	//卡号信息
	protected String card = "";
	// 积分
	protected String points = "";

	// 店主信息
	byte[] mValueRead30 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x03, (byte) 0x00, (byte) 0xa7 };
	protected String dianzhuInfo = "";
	// 店主密码信息
	byte[] mValueRead31 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x03, (byte) 0x01, (byte) 0xa6 };
	byte[] mValueRead32 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x03, (byte) 0x02, (byte) 0xa5 };
	byte[] mValueRead33 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x03, (byte) 0x03, (byte) 0xa4 };

	protected String password = "";
	// 超级管理员信息
	byte[] mValueRead40 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x04, (byte) 0x00, (byte) 0xa0 };
	//
	protected String admin = "";
	// 商店名称1
	byte[] mValueRead50 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x05, (byte) 0x00, (byte) 0xa1 };
	// 商店名称2
	byte[] mValueRead51 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x05, (byte) 0x01, (byte) 0xa0 };
	// 商店名称3
	byte[] mValueRead52 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x05, (byte) 0x02, (byte) 0xa3 };
	// 商店名称4
	byte[] mValueRead53 = { (byte) 0x9b, (byte) 0x0e, (byte) 0x00, (byte) 0x03,
			(byte) 0x32, (byte) 0x05, (byte) 0x03, (byte) 0xa2 };

	protected String info1 = "";
	protected String info2 = "";
	protected String info3 = "";
	protected String info4 = "";

	byte[] mValueToSend = { (byte) 0x9b, (byte) 0x0c, (byte) 0x00, (byte) 0x02,
			(byte) 0x30, (byte) 0x52, (byte) 0xf7 };

	byte[] mValueToChk1 = { (byte) 0x9b, (byte) 0x0d, (byte) 0x00, (byte) 0x09,
			(byte) 0x31, (byte) 0x60, (byte) 0x01, (byte) 0xff, (byte) 0xff,
			(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xcf };

	byte[] mValueToCheck2 = { (byte) 0x9b, (byte) 0x0d, (byte) 0x00,
			(byte) 0x09, (byte) 0x31, (byte) 0x60, (byte) 0x02, (byte) 0xff,
			(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
			(byte) 0xcc };
	byte[] mValueToCheck3 = { (byte) 0x9b, (byte) 0x0d, (byte) 0x00,
			(byte) 0x09, (byte) 0x31, (byte) 0x60, (byte) 0x03, (byte) 0xff,
			(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
			(byte) 0xcd };
	byte[] mValueToCheck4 = { (byte) 0x9b, (byte) 0x0d, (byte) 0x00,
			(byte) 0x09, (byte) 0x31, (byte) 0x60, (byte) 0x04, (byte) 0xff,
			(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
			(byte) 0xca };
	byte[] mValueToCheck5 = { (byte) 0x9b, (byte) 0x0d, (byte) 0x00,
			(byte) 0x09, (byte) 0x31, (byte) 0x60, (byte) 0x05, (byte) 0xff,
			(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
			(byte) 0xcb };

	protected SerialPort mSerialPort;
	protected OutputStream mOutputStream;
	private InputStream mInputStream;
	protected boolean mByteReceivedBack;
	protected Object mByteReceivedBackSemaphore = new Object();
	protected SendingThread mSendingThread;

	protected byte[] mReciveData = new byte[128];
	protected int j = 0;

	protected class SendingThread extends Thread {
		@Override
		public void run() {
			while (!isInterrupted()) {
				synchronized (mByteReceivedBackSemaphore) {
					mByteReceivedBack = false;
					int size;

					try {
						if (mOutputStream != null) {
							mOutputStream.write(mValueToSend);

							// mOutputStream.write(mValueToSend3);

							// mOutputStream.write(mValueRead10);
						} else {
							return;
						}

						byte[] buffer = new byte[64];
						if (mInputStream == null)
							return;
						size = mInputStream.read(buffer);
						if (size > 0) {
							boolean flag = xunka(buffer, size);
							if (flag) {
								mOutputStream.write(mValueToChk1);
								size = mInputStream.read(buffer);
								if (size > 0) {
									boolean yz = yanzheng(buffer, size);
									if (yz) {
										// 第一扇区第一块
										// System.out.println("读卡。。。。。。。。。。。。。。。!!!!!!!!!!!");
										mOutputStream.write(mValueRead10);
										// System.out.println("读卡21。。。。。。。。。。。。。。。!!!!!!!!!!!"+mInputStream);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
							/*					System.out
														.println("读取第1扇区第一块成功!!!!!!!!!!!data="
																+ dk);*/
											} else {
												// return;
											}
										}

									}
								}

								mOutputStream.write(mValueToCheck2);
								size = mInputStream.read(buffer);
								if (size > 0) {
									boolean yz = yanzheng(buffer, size);
									if (yz) {

										// 第2扇区第0块
										mOutputStream.write(mValueRead20);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
											/*	System.out
														.println("读取第2扇区第1块成功!!!!!!!!!!!会员身份证信息前18位=="
																+ dk);*/
												idcard1 = dk;
											} else {
												// return;
											}
										}
										// 第2扇区第2块
										mOutputStream.write(mValueRead21);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
								/*				System.out
														.println("读取第2扇区第2块成功!!!!!!!!!!!会员身份证信息后2位=="
																+ dk);*/
												idcard2 = dk;
											} else {
												// return;
											}
										}
										// 第2扇区第3块
										mOutputStream.write(mValueRead22);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
									/*			System.out
														.println("读取第2扇区第3块成功!!!!!!!!!!!=="
																+ dk);*/
												idcard2 = dk;
											} else {
												// return;
											}
										}
										// 第2扇区第4块
										mOutputStream.write(mValueRead23);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
											/*	System.out
														.println("读取第2扇区第4块成功!!!!!!!!!!!=="
																+ dk);*/
												idcard2 = dk;
											} else {
												// return;
											}
										}
									}
								}
								mOutputStream.write(mValueToCheck3);
								size = mInputStream.read(buffer);
								if (size > 0) {
									boolean yz = yanzheng(buffer, size);
									if (yz) {

										// 第3扇区第0块
										mOutputStream.write(mValueRead30);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
										/*		System.out
														.println("读取第3扇区第一块成功!!!!!!!!!!!店主信息="
																+ dk);*/
												dianzhuInfo = dk;
											} else {
												// return;
											}
										}

										// 第3扇区第2块
										mOutputStream.write(mValueRead31);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
											/*	System.out
														.println("读取第3扇区第一块成功!!!!!!!!!!!店主密码="
																+ dk);*/
												password = dk;
											} else {
												// return;
											}
										}

										// 第3扇区第2块 写入数据
/*										mOutputStream.write(mValueToWrite31);
										System.out
												.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx!!!!!!!!!!!1111=");
										size = mInputStream.read(buffer);
										System.out
												.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx!!!!!!!!!!!2222=");
										if (size > 0) {
											String dk = xieshuju(buffer, size);
											System.out
													.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx!!!!!!!!!!!3333="
															+ dk);
											if (dk != "") {
												System.out
														.println("写数据  到    第3扇区第一块成功!!!!!!!!!!!="
																+ dk);
												password = dk;
											} else {
												// return;
											}
										}*/

									}
								}

								mOutputStream.write(mValueToCheck4);
								size = mInputStream.read(buffer);
								if (size > 0) {
									boolean yz = yanzheng(buffer, size);
									if (yz) {
										// 第4扇区第一块
										// System.out.println("读卡。。。。。。。。。。。。。。。!!!!!!!!!!!");
										mOutputStream.write(mValueRead40);
										// System.out.println("读卡21。。。。。。。。。。。。。。。!!!!!!!!!!!"+mInputStream);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
												/*System.out
														.println("读取第4扇区第1块成功!!!!!!!!!!!管理员信息="
																+ dk);*/
												admin = dk;
											} else {
												// return;
											}
										}

									}
								}

								mOutputStream.write(mValueToCheck5);
								size = mInputStream.read(buffer);
								if (size > 0) {
									boolean yz = yanzheng(buffer, size);
									if (yz) {
										// 第5扇区第一块
										mOutputStream.write(mValueRead50);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
										/*		System.out
														.println("读取第5扇区第0块成功!!!!!!!!!!!店主卡信息1="
																+ dk);*/
												info1 = dk;
											} else {
												// return;
											}
										}

										mOutputStream.write(mValueRead51);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
											/*	System.out
														.println("读取第5扇区第1块成功!!!!!!!!!!!店主卡信息2="
																+ dk);*/
												info2 = dk;
											} else {
												// return;
											}
										}

										mOutputStream.write(mValueRead52);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
										/*		System.out
														.println("读取第5扇区第2块成功!!!!!!!!!!!店主卡信息3="
																+ dk);*/
												info3 = dk;
											} else {
												// return;
											}
										}
										mOutputStream.write(mValueRead53);
										size = mInputStream.read(buffer);
										if (size > 0) {
											String dk = duka(buffer, size);
											if (dk != "") {
											//	System.out
											//			.println("读取第5扇区第3块成功!!!!!!!!!!!店主卡信息4="
											//					+ dk);
												info4 = dk;
											} else {
												// return;
											}
										}

									}
								}

								if (idcard1 != "" && idcard2 != ""
										&& dianzhuInfo != "" && password != ""
										&& admin != "") {
									notifyActivity();
									return;
								}

							} else {
								// return ;
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
						return;
					}
				}
			}
		}
	}

	protected abstract void notifyActivity();
	
/*	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

        if (mSerialPort != null ) {
        	if(mSendingThread != null) {
        		mSendingThread.interrupt();
        	} 
        	mSendingThread = new SendingThread();
			mSendingThread.start();
		}
		
	}*/
	
	
	protected boolean xunka(byte[] buffer, int size) {
		boolean flag = false;
		synchronized (mByteReceivedBackSemaphore) {
			int i;
			for (i = 0; i < size; i++) {
				mReciveData[i] = buffer[i];
			}

			String result = String.format("%02x%02x", mReciveData[0],
					mReciveData[1]);
			if ("9b0c".equalsIgnoreCase(result)) {

				String success = String.format("%02x", mReciveData[5]);
				if ("00".equalsIgnoreCase(success)) {
					card = String.format(
							"%02x%02x%02x%02x",
							mReciveData[9], mReciveData[10], mReciveData[11],
							mReciveData[12]);
					flag = true;
				}

			}
		}
		return flag;
	}

	protected boolean yanzheng(byte[] buffer, int size) {
		boolean flag = false;
		synchronized (mByteReceivedBackSemaphore) {
			int i;
			for (i = 0; i < size; i++) {
				mReciveData[i] = buffer[i];
			}

			String result = String.format("%02x%02x", mReciveData[0],
					mReciveData[1]);
			if ("9b0d".equalsIgnoreCase(result)) {
				String success = String.format("%02x", mReciveData[5]);
				if ("00".equalsIgnoreCase(success)) {
					flag = true;
				}
			}
		}
		return flag;
	}

	protected String duka(byte[] buffer, int size) {
		String data = "";
		synchronized (mByteReceivedBackSemaphore) {
			int i;
			for (i = 0; i < size; i++) {
				mReciveData[i] = buffer[i];
			}

			String result = String.format("%02x%02x", mReciveData[0],
					mReciveData[1]);
			if ("9b0e".equalsIgnoreCase(result)) {

				String success = String.format("%02x", mReciveData[5]);

				if ("00".equalsIgnoreCase(success)) {
					for (int m = 6; m < 22; m++) {
						data += String.format("%02x", mReciveData[m]);
					}
				}
			}
		}
		return data;
	}

	protected String xieshuju(byte[] buffer, int size) {
		String data = "";
		synchronized (mByteReceivedBackSemaphore) {
			int i;
			for (i = 0; i < size; i++) {
				mReciveData[i] = buffer[i];
			}

			String result = String.format("%02x%02x", mReciveData[0],
					mReciveData[1]);
			if ("9b0f".equalsIgnoreCase(result)) {
				String success = String.format("%02x", mReciveData[5]);

				if ("00".equalsIgnoreCase(success)) {
					for (int m = 6; m < 22; m++) {
						data += String.format("%02x", mReciveData[m]);
					}
				}
			}
		}
		return data;
	}

	private void DisplayError(int resourceId) {
		AlertDialog.Builder b = new AlertDialog.Builder(this);
		b.setTitle("Error");
		b.setMessage(resourceId);
		b.setPositiveButton("OK", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// 在手机上操作。暂时注释掉
				// ReadSerialPort.this.finish();
			}
		});
		b.show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			test4052.testopen();
			test4052.testioctl(0);
			mSerialPort = new SerialPort(new File(Constants.SERIAL_PATH),
					Constants.SERIAL_BOUNDRATE, 0);
			mOutputStream = mSerialPort.getOutputStream();
			mInputStream = mSerialPort.getInputStream();

			/* Create a receiving thread */
			// mReadThread = new ReadThread();
			// mReadThread.start();

/*	        if (mSerialPort != null) {
	        	mSendingThread = new SendingThread();
				mSendingThread.start();
			}*/
		} catch (SecurityException e) {
			DisplayError(R.string.error_security);
		} catch (IOException e) {
			DisplayError(R.string.error_unknown);
		} catch (InvalidParameterException e) {
			DisplayError(R.string.error_configuration);
		}
	}

	protected abstract void onDataReceived(final byte[] buffer, final int size);

	@Override
	protected void onDestroy() {
		if (mSerialPort != null) {
			mSerialPort.close();
			if (mSendingThread != null)
				mSendingThread.interrupt();
		}
		mSerialPort = null;
		super.onDestroy();
	}
}
